//
//  FBDCaheManager.m
//  EDCsfzs
//
//  Created by feng on 16/9/21.
//  Copyright © 2016年 牛高航. All rights reserved.
//

#import "FBDCaheManager.h"
#import "NSString+Base64.m"
#import "BDFilePathTool.h"

static  FBDCaheManager* sigleTan;
static NSInteger MAXCACHETIME=60*60*24*10; //设置缓存的最大时间
@implementation FBDCaheManager
{

    NSFileManager* _fm;
}

/**
 单例的快速创建
 @return 工具类单例
 */
+(instancetype)defaultTools
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sigleTan=[[self alloc] init];
        sigleTan.countLimit=100;
        sigleTan->_fm=[NSFileManager defaultManager];
    });
    return sigleTan;
}
//存值
-(void)fbdCacheSetObject:(id)data forKey:(NSString*)key
{
    if (data&&key)
    {
        key=[key base64EncodedString];
        
        //先存内存中
        NSData*resultData=[NSKeyedArchiver archivedDataWithRootObject:data];
        [self setObject:resultData forKey:key];
        //再存disk中
        NSString *filename = [BD_CacheDir stringByAppendingPathComponent:key];
        BOOL isDir = YES;
        if (![_fm fileExistsAtPath:BD_CacheDir isDirectory:&isDir]) {
            [_fm createDirectoryAtPath:BD_CacheDir withIntermediateDirectories:NO attributes:nil error:nil];
            
        }
        
        NSError *error;
        @try {
            
            [resultData writeToFile:filename options:NSDataWritingAtomic error:&error];
            
        }
        @catch (NSException * e) {
            //TODO: error handling maybe
        }
    }
}
//取值
-(id)fbdCacheObjectForKey:(NSString*)key
{
    key=[key base64EncodedString];
    NSString* filePath=[BD_CacheDir stringByAppendingPathComponent:key];
    //先从内存中取
    NSData* resultData=[self objectForKey:key];
    //再从disk中取
    if(!resultData)
    {
        if ([_fm fileExistsAtPath:filePath])
        {
            NSDate *modificationDate = [[_fm attributesOfItemAtPath:filePath error:nil] objectForKey:NSFileModificationDate];
            //如果超过缓存的最大保留时间就删除缓存
            if ([modificationDate timeIntervalSinceNow]>MAXCACHETIME)
            {
                [_fm removeItemAtPath:filePath error:nil];
                return nil;
            }
            resultData=[NSData dataWithContentsOfFile:filePath];
        }
        else
        {
            return nil;
        }
    }
    
    id unArchResult=[NSKeyedUnarchiver unarchiveObjectWithData:resultData];
    if (unArchResult) {
        return unArchResult;
    }
    return nil;
}

//清缓存
-(void)fbdClearCache
{
    //先把内存清除
    [self removeAllObjects];
    //再把disk清除
    NSError*error=nil;
    if ([_fm fileExistsAtPath:BD_CacheDir])
    {
        [_fm removeItemAtPath:BD_CacheDir error:&error];
        if (error) {
            NSLog(@"%s  fengbaodong:Error log is  %@  ",__func__ ,error.localizedDescription);
        }    
    }


}
//计算缓存大小
-(float)fbdGetCacheSize
{
    float sizeDir=[BDFilePathTool  getDirSizeAtPath:BD_CacheDir];
    return sizeDir;
}

@end
